using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MvcDemo.Db;
using MvcDemo.Models;
using MvcDemo.Repository;
using MvcDemo.ResultModel;

namespace MvcDemo.Controllers
{
    public class ProductController:Controller
    {
        private readonly EfRepository<Product> _db;
        public ProductController()
        {
            _db = new EfRepository<Product>();

            var ReCate = new EfRepository<Category>(); 
            var category = ReCate.Table.Where(x=>x.IsDeleted==false).FirstOrDefault();
            if(category==null)
            {
                ReCate.Insert(new Category{
                    CategoryName = "食品"
                });
            }
        }
        public IActionResult Index()
        {
            var product = _db.Table.Where(x=>x.IsDeleted==false).ToArray();
            return View(product);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var product = _db.GetById(id);
            return View(product);
        }
        public IActionResult Delete(int id)
        {
            _db.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Save(Product product)
        {
            if(product==null || product.Id<=0)
            {
                _db.Insert(product);
            }else{
                _db.Update(product);
            }
            return Ok();
        }
        public IActionResult Query(Keyword keyword)
        {
            var db = new EfRepository<Product>();
            List<Product> products;
            if(keyword.word==null || keyword.word.Length<=0)
            {
                products=db.Table.Where(x=>x.IsDeleted==false).ToList();
            }else{
                products=db.Table.Where(x=>x.IsDeleted==false && x.ProductName.Contains(keyword.word)).ToList();
            }
            return Json(products);
        }
        
    }
}